package com.example.demo.leetcode;

import java.util.*;

/**
 * https://leetcode.cn/problems/sliding-window-maximum/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/03/04 9:04
 */
public class _239_滑动窗口最大值 {

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        int k = 3;

        int[] nums1 = {1};
        int k1 = 1;

        int[] nums2 = {1, -1};
        int k2 = 1;

        int[] ints = maxSlidingWindow1(nums2, k2);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] maxSlidingWindow(int[] nums, int k) {
        int[] res = new int[nums.length - k + 1];
        List<Integer> temp = new LinkedList<>();
        for (int i = 0; i < k; i++) {
            temp.add(nums[i]);
        }
        res[0] = temp.stream().max(Integer::compare).get();

        for (int i = k; i < nums.length; i++) {
            temp.remove(0);
            temp.add(nums[i]);
            res[i - k + 1] = temp.stream().max(Integer::compare).get();
        }
        return res;
    }


    public static int[] maxSlidingWindow1(int[] nums, int k) {
        int[] res = new int[nums.length - k + 1];
        Queue<int[]> temp = new PriorityQueue<>((int[] o1, int[] o2) -> o2[0] - o1[0]);
        for (int i = 0; i < k; i++) {
            temp.offer(new int[]{nums[i], i});
        }
        res[0] = temp.peek()[0];
        for (int i = k; i < nums.length; i++) {
            temp.offer(new int[]{nums[i], i});
            while (temp.peek()[1] <= i - k) {
                temp.poll();
            }
            res[i - k + 1] = temp.peek()[0];
        }
        return res;
    }


}
